from flask import Flask, request, jsonify, render_template
from flask_cors import CORS
from flask_socketio import SocketIO, emit
import threading
import queue
import sys
import io
import traceback
from debugger import PythonDebugger

app = Flask(__name__)
app.config['SECRET_KEY'] = 'weboj_debugger_secret'
CORS(app)
socketio = SocketIO(app, cors_allowed_origins="*")

# 全局调试器实例
debugger_instance = None

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/api/start_debug', methods=['POST'])
def start_debug():
    global debugger_instance
    
    data = request.get_json()
    code = data.get('code', '')
    
    if not code:
        return jsonify({'error': 'No code provided'}), 400
    
    try:
        # 创建新的调试器实例
        debugger_instance = PythonDebugger(code, socketio)
        debugger_instance.start()
        
        return jsonify({
            'status': 'success',
            'message': 'Debugger started successfully'
        })
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/step', methods=['POST'])
def step():
    global debugger_instance
    
    if not debugger_instance:
        return jsonify({'error': 'No active debugger session'}), 400
    
    try:
        result = debugger_instance.step()
        return jsonify(result)
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/continue', methods=['POST'])
def continue_execution():
    global debugger_instance
    
    if not debugger_instance:
        return jsonify({'error': 'No active debugger session'}), 400
    
    try:
        result = debugger_instance.continue_execution()
        return jsonify(result)
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/get_variables', methods=['GET'])
def get_variables():
    global debugger_instance
    
    if not debugger_instance:
        return jsonify({'error': 'No active debugger session'}), 400
    
    try:
        variables = debugger_instance.get_variables()
        return jsonify({'variables': variables})
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/set_breakpoint', methods=['POST'])
def set_breakpoint():
    global debugger_instance
    
    data = request.get_json()
    line_number = data.get('line_number')
    
    if not debugger_instance:
        return jsonify({'error': 'No active debugger session'}), 400
    
    if line_number is None:
        return jsonify({'error': 'Line number is required'}), 400
    
    try:
        result = debugger_instance.set_breakpoint(line_number)
        return jsonify(result)
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/remove_breakpoint', methods=['POST'])
def remove_breakpoint():
    global debugger_instance
    
    data = request.get_json()
    line_number = data.get('line_number')
    
    if not debugger_instance:
        return jsonify({'error': 'No active debugger session'}), 400
    
    if line_number is None:
        return jsonify({'error': 'Line number is required'}), 400
    
    try:
        result = debugger_instance.remove_breakpoint(line_number)
        return jsonify(result)
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/stop_debug', methods=['POST'])
def stop_debug():
    global debugger_instance
    
    if debugger_instance:
        debugger_instance.stop()
        debugger_instance = None
    
    return jsonify({'status': 'success', 'message': 'Debugger stopped'})

@socketio.on('connect')
def handle_connect():
    print('Client connected')
    emit('status', {'message': 'Connected to debugger'})

@socketio.on('disconnect')
def handle_disconnect():
    print('Client disconnected')

if __name__ == '__main__':
    socketio.run(app, debug=True, host='0.0.0.0', port=5000) 